package com.seasugar.raggie.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seasugar.raggie.common.R;
import com.seasugar.raggie.model.dto.DishDto;
import com.seasugar.raggie.model.entity.Category;
import com.seasugar.raggie.model.entity.Dish;
import com.seasugar.raggie.model.entity.DishFlavor;
import com.seasugar.raggie.model.vo.DishVo;
import com.seasugar.raggie.service.CategoryService;
import com.seasugar.raggie.service.DishFlavorService;
import com.seasugar.raggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("page")
    public R getAllDish(Integer page, Integer pageSize, String name) {
        log.info("页数:{},条数:{}", page, pageSize);

//        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page pageInfo = new Page(page, pageSize);
        //准备将得到数据的page全赋给新page并加入新数据
        Page<DishVo> dishVoPageInfo = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getSort, Dish::getUpdateTime);
        //获得dish分页数据
        dishService.page(pageInfo, queryWrapper);
        //拷贝
        BeanUtils.copyProperties(pageInfo, dishVoPageInfo, "records");
        /* 错误代码段
        BeanUtils.copyProperties(pageInfo,dishVoPageInfo);
        List<DishVo> records = dishVoPageInfo.getRecords();
         for (DishVo record : records) {
            说是copy出来的dishVoPageInfo里的对象还是Dish，不是DishVo，不能遍历
        }
         */
        //新添数据
        List<DishVo> list = new LinkedList<>();
        List<Dish> records = pageInfo.getRecords();
        for (Dish record : records) {
            DishVo dishVo = new DishVo();
            BeanUtils.copyProperties(record, dishVo);
//            log.info(String.valueOf(dishVo.getCategoryId()));
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishVo.setCategoryName(category.getName());
                list.add(dishVo);
            }
        }
        dishVoPageInfo.setRecords(list);

        return R.success(dishVoPageInfo);
    }

    /**
     * 添加菜品
     */
    @PostMapping
    //涉及多表操作应该加事务，否则会出现问题，应该在业务层处理
    public R addDish(@RequestBody DishDto dishDto) {
        log.info("添加菜品名称:{}", dishDto.getName());
        boolean b = dishService.insertDish(dishDto);
        //清理redis
        if (b) {
            String key="dish:"+dishDto.getCategoryId();
            redisTemplate.delete(key);
            return R.success("添加成功");
        }
        else
            return R.error("添加失败");
    }

    /**
     * 根据菜品id获取菜品
     */
    @GetMapping("{id}")
    public R updateDish(@PathVariable("id") Long id) {
        log.info("修改菜品id:{}", id);
        Dish dish = dishService.getDishVoById(id);
        if (dish != null)
            return R.success(dish);
        else
            return R.error("没有该菜品");
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public R getDishById(@RequestBody DishDto dishDto) {
        log.info("修改菜品id:{}", dishDto.getId());
        boolean b = dishService.updateDish(dishDto);
        if (b) {
            String key = "dish:" + dishDto.getCategoryId();
            redisTemplate.delete(key);
            return R.success("修改成功");
        }
        else
            return R.error("修改失败");
    }

    /**
     * 删除菜品
     * 应该把dish_flavor表中的相应数据以及外键关联表也进行删除
     * 可以写sql语句完成，但是我现在不会
     */
    @DeleteMapping
    public R deleteDish(String ids) {
        log.info("删除菜品id:{}", ids);
        //String转为List
        String[] id = StringUtils.split(ids, ',');
        List<String> list = Arrays.asList(id);
        List<Dish> dishes = dishService.deleteByIds(list);
//        boolean b = dishService.removeByIds(Collections.singleton(ids));
        for (Dish dish : dishes) {
            String key="dish:"+dish.getCategoryId();
            redisTemplate.delete(key);
        }
        return R.success("删除成功");
    }


    /**
     * 改变菜品销售状态
     */
    @PostMapping("status/{status}")
    public R updateStatus(@PathVariable("status") Integer status, String ids) {
        log.info("改变菜品状态id:{}", ids);
        //String转为List
        String[] id = StringUtils.split(ids, ',');
        List<Dish> list = new LinkedList<>();
        for (String i : id) {
            list.add(new Dish(Long.parseLong(i), status));
            Dish dish = dishService.getById(i);
            String key = "dish:" + dish.getCategoryId();
            redisTemplate.delete(key);
        }
        boolean b = dishService.updateBatchById(list);
        if (b)
            return R.success("修改成功");
        else
            return R.error("修改失败");
    }

    @GetMapping("list")
    public R dish(Long categoryId) {
        List<DishDto> dishDtoList=null;
        //redis优化
        String key="dish:"+categoryId;
        //从redis中获取霍村数据
        //将json字符串转换为List对象
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //redis中不存在
        //获取分类下的菜品
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        //status为0表示停售，不予查询
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort,Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        if (list != null) {
            List<DishVo> res=new LinkedList<>();
            for (Dish dish : list) {
                DishVo dishVo = new DishVo();
                BeanUtils.copyProperties(dish, dishVo);
                LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(DishFlavor::getDishId, dish.getId());
                List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
                dishVo.setFlavors(dishFlavors);
                res.add(dishVo);
            }
            //将查询到的list缓存到redis
            redisTemplate.opsForValue().set(key,res,60, TimeUnit.MINUTES);
            return R.success(res);
        }
        else
            return R.error("获取失败");
    }
}
